package cn.toma.controller.sys;

import cn.toma.common.annotation.Log;
import cn.toma.common.exception.FfBootException;
import cn.toma.common.utils.StringUtils;
import cn.toma.common.vo.QueryRequest;
import cn.toma.common.vo.StringPool;
import cn.toma.config.web.utli.BaseController;
import cn.toma.config.web.utli.MD5Util;
import cn.toma.model.sys.User;
import cn.toma.service.sys.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.startup.UserConfig;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Map;

@Slf4j
@Validated
@RestController
@RequestMapping("user")
public class UserController extends BaseController
{

	private String message;

	@Autowired
	private UserService userService;

	@GetMapping("check/{username}")
	public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String username)
	{
		return this.userService.findByName(username) == null;
	}

	@GetMapping("/{username}")
	public User detail(@NotBlank(message = "{required}") @PathVariable String username)
	{
		return this.userService.findByName(username);
	}

	@GetMapping
	@RequiresPermissions("user:view")
	public Map<String, Object> userList(QueryRequest queryRequest, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize, User user)
	{
		String onlineUser = getOnlineUser();
		log.info("当前用户为: {}", onlineUser);
		Page<User> objects = PageHelper.startPage(pageNum, pageSize);
		StringUtils.sortOrderBy(queryRequest, objects,"u.");
		userService.findUserDetail(user);
		return getDataTable(objects.toPageInfo());
	}

	@Log("新增用户")
	@PostMapping
	@RequiresPermissions("user:add")
	public void addUser(@Valid User user) throws FfBootException
	{
		try {
			user.setPassword(MD5Util.encrypt(user.getUsername(), User.DEFAULT_PASSWORD));
			this.userService.createUser(user);
		} catch (Exception e) {
			message = "新增用户失败";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

	@Log("修改用户")
	@PutMapping
	@RequiresPermissions("user:update")
	public void updateUser(@Valid User user) throws FfBootException
	{
		try {
			this.userService.updateUser(user);
		} catch (Exception e) {
			message = "修改用户失败";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

	@Log("删除用户")
	@DeleteMapping("/{userIds}")
	@RequiresPermissions("user:delete")
	public void deleteUsers(@NotBlank(message = "{required}") @PathVariable String userIds) throws FfBootException
	{
		try {
			String[] ids = userIds.split(StringPool.COMMA);
			this.userService.deleteUsers(ids);
		} catch (Exception e) {
			message = "删除用户失败";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

	@PutMapping("profile")
	public void updateProfile(@Valid User user) throws FfBootException
	{
		try {
			this.userService.updateProfile(user);
		} catch (Exception e) {
			message = "修改个人信息失败";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

	@PutMapping("avatar")
	public void updateAvatar(
			@NotBlank(message = "{required}") String username,
			@NotBlank(message = "{required}") String avatar) throws FfBootException
	{
		try {
			this.userService.updateAvatar(username, avatar);
		} catch (Exception e) {
			message = "修改头像失败";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}


	@GetMapping("password/check")
	public boolean checkPassword(
			@NotBlank(message = "{required}") String username,
			@NotBlank(message = "{required}") String password)
	{
		String encryptPassword = MD5Util.encrypt(username, password);
		User user = userService.findByName(username);
		if (user != null)
			return StringUtils.equals(user.getPassword(), encryptPassword);
		else
			return false;
	}

	@PutMapping("password")
	public void updatePassword(
			@NotBlank(message = "{required}") String username,
			@NotBlank(message = "{required}") String password) throws FfBootException
	{
		try {
			String encrypt = MD5Util.encrypt(username, password);
			userService.updatePassword(username, encrypt);
		} catch (Exception e) {
			message = "修改密码失败";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

	@PutMapping("password/reset")
	@RequiresPermissions("user:reset")
	public void resetPassword(@NotBlank(message = "{required}") String usernames) throws FfBootException
	{
		try {
			String[] usernameArr = usernames.split(StringPool.COMMA);
			String encrypt = MD5Util.encrypt(usernames, User.DEFAULT_PASSWORD);
			this.userService.resetPassword(usernameArr, encrypt);
		} catch (Exception e) {
			message = "重置用户密码失败";
			log.error(message, e);
			throw new FfBootException(message);
		}
	}

   /* @PostMapping("excel")
    @RequiresPermissions("user:export")
    public void export(QueryRequest queryRequest, User user, HttpServletResponse response) throws FfBootException {
        try {
            List<User> users = this.userService.findUserDetail(user, queryRequest).getRecords();
            ExcelKit.$Export(User.class, response).downXlsx(users, false);
        } catch (Exception e) {
            message = "导出Excel失败";
            log.error(message, e);
            throw new FfBootException(message);
        }
    }*/

   public static void main(String[] args){
	   String admin = MD5Util.encrypt("admin", User.DEFAULT_PASSWORD);
	   log.info(admin);
   }
}
